const express = require('express');
const path = require('path');
const webpack = require('webpack');
const devMiddleware = require('webpack-dev-middleware');
const hotMiddleware = require('webpack-hot-middleware');
const app = express();

// 从webpack.dev.js中读取配置文件 和devserver配置
const { webpackConfig, DEV_SERVER_CONFIG } = require('./config/webpack.dev.js');

const compiler = webpack(webpackConfig);

// 指定静态文件目录
app.use(express.static(path.join(__dirname, '../public/dist')));

// devMiddleware 中间件（监控文件改动）
app.use(devMiddleware(compiler, {

  writeToDisk: (filePath) => filePath.endsWith('.tpl'),
  publicPath: webpackConfig.output.publicPath,
  headers: { 
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
    'Access-Control-Allow-Headers': 'X-Requested-With,content-type, Authorization',
  },
  stats: {
    colors: true
  }
}));

// hotMiddleware 中间件（热更新）
app.use(hotMiddleware(compiler, {
  path: `/${DEV_SERVER_CONFIG.HMR_PATH}`,
  log: (msg) => {
    console.log(`[HMR] ${msg}`);
  }
}));

console.log("请等待webpack构建完成提示...");

const port = DEV_SERVER_CONFIG.PORT;

app.listen(port, () => {
  console.log(`webpack构建完成，正在监听${port}端口...`);
});